package util;

import java.beans.PropertyDescriptor;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.cglib.beans.BeanGenerator;
import net.sf.cglib.core.ReflectUtils;

import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;

import com.yellowbook.common.utils.LocalProxy;

/**
 * Created by IntelliJ IDEA. User: chokkh01 Date: Dec 23, 2008 Time: 1:09:01 PM
 * To change this template use File | Settings | File Templates.
 */
public class StringUtil {

	/**
	 * utility function to construct a list of ids
	 * 
	 * @param ids
	 * @return
	 */
	public static String idsToInString(int[] ids) {
		if (ids.length == 0)
			return "";
		StringBuffer sb = new StringBuffer();
		sb.append(ids[0]);
		for (int i = 1; i < ids.length; i++) {
			sb.append(',');
			sb.append(ids[i]);
		}
		return sb.toString();
	}

	/**
	 * utility function to construct a list of ids
	 * 
	 * @param ids
	 * @return
	 */
	public static String idsToInString(Integer[] ids) {
		if (ids.length == 0)
			return "";
		StringBuffer sb = new StringBuffer();
		sb.append(ids[0]);
		for (int i = 1; i < ids.length; i++) {
			sb.append(',');
			sb.append(ids[i]);
		}
		return sb.toString();
	}

	/**
	 * utility function to construct a comma seperated String from a String
	 * Array
	 * 
	 * @param strArr
	 * @return
	 */
	public static String arrayToCommaSeperatedString(String[] strArr) {
		if (strArr == null || strArr.length == 0) {
			return null;
		}
		StringBuffer sb = new StringBuffer();
		sb.append(strArr[0]);
		for (int i = 1; i < strArr.length; i++) {
			sb.append(',');
			sb.append(strArr[i]);
		}
		return sb.toString();
	}

	/**
	 * utility function to construct a comma seperated String from a String
	 * Array
	 * 
	 * @param intArr
	 * @return
	 */
	public static String arrayToCommaSeperatedString(Integer[] intArr) {
		if (intArr == null || intArr.length == 0) {
			return null;
		}
		StringBuffer sb = new StringBuffer();
		sb.append(intArr[0]);
		for (int i = 1; i < intArr.length; i++) {
			sb.append(',');
			sb.append(intArr[i].intValue());
		}
		return sb.toString();
	}

	/**
	 * To validate the passed in string to see if it is a valid set of integer
	 * values. If so, we generate the in string or else we throw an error.
	 * 
	 * @param strIds
	 * @return
	 */
	public static String toValidatedInString(String strIds) {
		if (strIds.length() == 0) {
			return "";
		}

		StringBuffer sb = new StringBuffer();
		StringTokenizer commaSepStrTokens = new StringTokenizer(strIds, ", ");
		while (commaSepStrTokens.hasMoreTokens()) {
			String strValue = commaSepStrTokens.nextToken().trim();
			if (strValue.equals("")) {
				continue;
			} else {
				int intValue = Integer.parseInt(strValue);
				sb.append(intValue + ",");
			}
		}
		String retVal = "";
		if (sb.length() > 0) {
			retVal = sb.substring(0, (sb.length() - 1));
		}
		return retVal;
	}

	public static String getNewDelimitedEmailStr(String emailStr,
			String regExStr, String newDelim) {
		String newEmailStr = null;
		if (emailStr != null && regExStr != null && newDelim != null) {
			String[] emailAddArr = emailStr.split(regExStr);
			for (String emailAddress : emailAddArr) {
				emailAddress = emailAddress.trim();
				if (emailAddress.length() > 0) {
					if (newEmailStr == null) {
						newEmailStr = emailAddress;
					} else {
						newEmailStr += newDelim + emailAddress;
					}
				}
			}
		}
		return newEmailStr;
	}

	public static final String cut(String text, int requiredLength) {
		try {
			return StringUtils.abbreviate(text, requiredLength);
		} catch (IllegalArgumentException e) {
			return text != null && text.length() > requiredLength ? text
					.substring(0, requiredLength) : text;
		}
	}

	/**
	 * DBC case -> SBC case space in SBC is 12288, while DBC is 32 And the minus
	 * between other DBC chars(33-126) and SBC chars(65281-65374) is 65248
	 * 
	 * @param SBCstr
	 * @return
	 */
	public static final String DBC2SBC(String DBCstr) {
		char[] c = DBCstr.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 32) {
				c[i] = (char) 12288;
				continue;
			}
			if (c[i] < 127)
				c[i] = (char) (c[i] + 65248);
		}
		return new String(c);
	}

	/**
	 * SBC case -> DBC case space in SBC is 12288, while DBC is 32 And the minus
	 * between other DBC chars(33-126) and SBC chars(65281-65374) is 65248
	 * 
	 * @param SBCstr
	 * @return
	 */
	public static final String SBC2DBC(String SBCstr) {
		char[] c = SBCstr.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 12288) {
				c[i] = (char) 32;
				continue;
			}
			if (c[i] > 65280 && c[i] < 65375)
				c[i] = (char) (c[i] - 65248);
		}
		return new String(c);
	}

	public static void main(String[] args) throws IOException, ParseException {
		// File f = new File("target/classes/helloworld/HelloWorld.class");
		// BufferedReader r = new BufferedReader(new FileReader(f));
		// String s = null;
		// while ((s = r.readLine()) != null) {
		// System.out.println(s);
		// }
		// FileInputStream fis = new
		// FileInputStream("target/classes/helloworld/HelloWorld.class");
		// int length = fis.available(); //文件数据
		// byte[] data = new byte[length]; //读取文件到字节数组
		// fis.read(data); //关闭文件
		// fis.close(); //解析文件数据
		// parseFile(data);
		// Pattern p = Pattern.compile("s(\\d)(\\d*)");
		// Matcher m = p.matcher("s4");
		// if(m.matches()) {
		// System.out.println(m.group(1));
		// System.out.println(m.group(2));
		// System.out.println(m.groupCount());
		// }
//		indexOf("adebcdefg","def",0);
		byte[] bs = {-1};
		byte[] bs1 = new String(bs, "UTF-8").getBytes("UTF-8");
		System.out.println(Arrays.toString(bs1));
		/*
		String url = "http://dev.virtualearth.net/REST/V1/Imagery/Map/Road/space needle seattle?mapLayer=TrafficFlow&format=jpeg&key=AmTnKaIe4oBzLQemNpFRNlNYVxJ3J54OjYnHdxlAgZTmiiQitdlpAMJIgvBp95mn";
		String charset = "UTF-8";
		url = URIUtil.encodeQuery(url, charset);

		byte[] bytes = doGetAsBytes(url);
		System.out.println(Arrays.toString(bytes));
		String s = new String(bytes, "UTF-8");
		System.out.println(s);
		
		byte[] bs1 = s.getBytes("UTF-8");
		System.out.println(Arrays.toString(bs1));
		*/
		//FileUtil.writeFileByBytes("folder/bingmap.jpeg", bytes);
	}

	public static HttpGet initGetMethod(String url){
		HttpGet hg = new HttpGet(url);
		
//		hg.getParams().setParameter(CoreProtocolPNames.USER_AGENT, HttpClientConstants.USER_AGENT);
		
		return hg;
	}

	public static byte[] doGetAsBytes(String url){
		HttpClient httpClient = new DefaultHttpClient();
		HttpHost proxy = new HttpHost(LocalProxy.HOST, LocalProxy.PORT);
		httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
                proxy);
		HttpGet hg = initGetMethod(url);
		
		HttpResponse response = null;
		HttpEntity entity = null;
		byte[] bytes = null;
		try {
			response = httpClient.execute(hg);
			if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				entity = response.getEntity();
				bytes = EntityUtils.toByteArray(entity);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			httpClient.getConnectionManager().shutdown();
		}
		
		return bytes;
	}

	  public static int indexOf(String src, String str, int fromIndex) {
	        return indexOf(src.toCharArray(), 0, src.length(),
	                       str.toCharArray(), 0, str.length(), fromIndex);
	    }
	static int indexOf(char[] source, int sourceOffset, int sourceCount,
			char[] target, int targetOffset, int targetCount, int fromIndex) {
		if (fromIndex >= sourceCount) {
			return (targetCount == 0 ? sourceCount : -1);
		}
		if (fromIndex < 0) {
			fromIndex = 0;
		}
		if (targetCount == 0) {
			return fromIndex;
		}

		char first = target[targetOffset];
		int max = sourceOffset + (sourceCount - targetCount);

		for (int i = sourceOffset + fromIndex; i <= max; i++) {
			/* Look for first character. */
			if (source[i] != first) {
				while (++i <= max && source[i] != first)
					;
			}

			/* Found first character, now look at the rest of v2 */
			if (i <= max) {
				int j = i + 1;
				int end = j + targetCount - 1;
				for (int k = targetOffset + 1; j < end
						&& source[j] == target[k]; j++, k++)
					;

				if (j == end) {
					/* Found whole string. */
					return i - sourceOffset;
				}
			}
		}
		return -1;
	}

	private static void parseFile(byte[] data) {
		// 输出魔数
		/*
		 * System.out.println("http://www.a.com/abc".replaceAll("/+$", ""));
		 * System.out.print("魔数(magic):0x");
		 * System.out.print(Integer.toHexString(data[0]).substring(6)
		 * .toUpperCase());
		 * System.out.print(Integer.toHexString(data[1]).substring(6)
		 * .toUpperCase());
		 * System.out.print(Integer.toHexString(data[2]).substring(6)
		 * .toUpperCase());
		 * System.out.println(Integer.toHexString(data[3]).substring(6)
		 * .toUpperCase()); // 主版本号和次版本号码 int minor_version = (((int) data[4])
		 * << 8) + data[5]; int major_version = (((int) data[6]) << 8) +
		 * data[7]; System.out.println("版本号(version):" + major_version + "." +
		 * minor_version);
		 */
	}
	
}